from rest_framework import permissions
from rest_framework.permissions import BasePermission
from django.contrib.auth.decorators import user_passes_test
from functools import wraps
from .cache import CacheManager
import logging

logger = logging.getLogger(__name__)


class HasPermission(BasePermission):
    """检查用户是否有指定权限"""
    
    def __init__(self, permission_code):
        self.permission_code = permission_code
    
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        
        if request.user.is_superuser:
            return True
        
        # 使用缓存获取用户权限
        user_permissions = CacheManager.get_user_permissions(request.user.id)
        return self.permission_code in user_permissions


class HasRole(BasePermission):
    """检查用户是否有指定角色"""
    
    def __init__(self, role_code):
        self.role_code = role_code
    
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        
        if request.user.is_superuser:
            return True
        
        # 使用缓存获取用户角色
        user_roles = CacheManager.get_user_roles(request.user.id)
        return self.role_code in user_roles


class HasAnyPermission(BasePermission):
    """检查用户是否有任意一个指定权限"""
    
    def __init__(self, permission_codes):
        self.permission_codes = permission_codes if isinstance(permission_codes, list) else [permission_codes]
    
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        
        if request.user.is_superuser:
            return True
        
        user_permissions = CacheManager.get_user_permissions(request.user.id)
        return any(perm in user_permissions for perm in self.permission_codes)


class HasAllPermissions(BasePermission):
    """检查用户是否有所有指定权限"""
    
    def __init__(self, permission_codes):
        self.permission_codes = permission_codes if isinstance(permission_codes, list) else [permission_codes]
    
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        
        if request.user.is_superuser:
            return True
        
        user_permissions = CacheManager.get_user_permissions(request.user.id)
        return all(perm in user_permissions for perm in self.permission_codes)


class IsOwnerOrReadOnly(BasePermission):
    """只有对象所有者可以编辑，其他人只读"""
    
    def has_object_permission(self, request, view, obj):
        # 读权限对所有人开放
        if request.method in permissions.SAFE_METHODS:
            return True
        
        # 写权限只给对象所有者
        return obj.owner == request.user


# 装饰器函数
def require_permission(permission_code):
    """权限装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if not request.user.is_authenticated:
                from django.http import JsonResponse
                return JsonResponse({
                    'success': False,
                    'message': '未授权访问'
                }, status=401)
            
            if request.user.is_superuser:
                return view_func(request, *args, **kwargs)
            
            user_permissions = CacheManager.get_user_permissions(request.user.id)
            if permission_code not in user_permissions:
                from django.http import JsonResponse
                return JsonResponse({
                    'success': False,
                    'message': '权限不足'
                }, status=403)
            
            return view_func(request, *args, **kwargs)
        return wrapper
    return decorator


def require_role(role_code):
    """角色装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if not request.user.is_authenticated:
                from django.http import JsonResponse
                return JsonResponse({
                    'success': False,
                    'message': '未授权访问'
                }, status=401)
            
            if request.user.is_superuser:
                return view_func(request, *args, **kwargs)
            
            user_roles = CacheManager.get_user_roles(request.user.id)
            if role_code not in user_roles:
                from django.http import JsonResponse
                return JsonResponse({
                    'success': False,
                    'message': '权限不足'
                }, status=403)
            
            return view_func(request, *args, **kwargs)
        return wrapper
    return decorator


def require_any_permission(*permission_codes):
    """需要任意一个权限的装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if not request.user.is_authenticated:
                from django.http import JsonResponse
                return JsonResponse({
                    'success': False,
                    'message': '未授权访问'
                }, status=401)
            
            if request.user.is_superuser:
                return view_func(request, *args, **kwargs)
            
            user_permissions = CacheManager.get_user_permissions(request.user.id)
            if not any(perm in user_permissions for perm in permission_codes):
                from django.http import JsonResponse
                return JsonResponse({
                    'success': False,
                    'message': '权限不足'
                }, status=403)
            
            return view_func(request, *args, **kwargs)
        return wrapper
    return decorator


class PermissionMiddleware:
    """权限中间件"""
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        # 在视图处理之前
        self.process_request(request)
        
        response = self.get_response(request)
        
        # 在视图处理之后
        return response
    
    def process_request(self, request):
        """处理请求"""
        if request.user.is_authenticated:
            # 将用户权限和角色添加到请求对象中，方便后续使用
            request.user_permissions = CacheManager.get_user_permissions(request.user.id)
            request.user_roles = CacheManager.get_user_roles(request.user.id)
            
            logger.debug(f"User {request.user.username} permissions: {request.user_permissions}")
            logger.debug(f"User {request.user.username} roles: {request.user_roles}")


# 便捷的权限检查函数
def has_permission(user, permission_code):
    """检查用户是否有指定权限"""
    if not user.is_authenticated:
        return False
    
    if user.is_superuser:
        return True
    
    user_permissions = CacheManager.get_user_permissions(user.id)
    return permission_code in user_permissions


def has_role(user, role_code):
    """检查用户是否有指定角色"""
    if not user.is_authenticated:
        return False
    
    if user.is_superuser:
        return True
    
    user_roles = CacheManager.get_user_roles(user.id)
    return role_code in user_roles
